package com.meitianhui.convenitenbuy.module.home.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.IdRes;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.meitianhui.convenitenbuy.App;
import com.meitianhui.convenitenbuy.Constants;
import com.meitianhui.convenitenbuy.R;
import com.meitianhui.convenitenbuy.base.BaseToolbarActivity;
import com.meitianhui.convenitenbuy.config.InfoProvider;
import com.meitianhui.convenitenbuy.module.home.contract.OpenFightGroupContract;
import com.meitianhui.convenitenbuy.module.home.di.DaggerHomeComponent;
import com.meitianhui.convenitenbuy.module.home.di.HomeModule;
import com.meitianhui.convenitenbuy.module.home.model.bean.GoodsInfoDetail;
import com.meitianhui.convenitenbuy.module.home.presenter.OpenFightGroupPresenter;
import com.meitianhui.convenitenbuy.module.mine.model.ConsumerAddress;
import com.meitianhui.convenitenbuy.module.mine.ui.activity.ReceivingAddressActivity;
import com.meitianhui.convenitenbuy.module.wallet.model.PayResultBean;
import com.meitianhui.convenitenbuy.util.AddressUtil;
import com.meitianhui.convenitenbuy.util.GlideUtils;
import com.meitianhui.convenitenbuy.util.RxBus;
import com.meitianhui.convenitenbuy.util.RxUtils;
import com.meitianhui.convenitenbuy.util.TipUtils;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.List;

import javax.inject.Inject;

import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

/**
 * Created by Administrator on 2017/11/17.
 */

public class OpenFightGroupActivity extends BaseToolbarActivity implements OpenFightGroupContract.View,RadioGroup.OnCheckedChangeListener {
    public static final int RESULT_INTENT = 0001;
    private RadioGroup mRadioGroup;
    private String mGoodsId, mJson;
    private ImageView mIvGood;
    private TextView mTvGoodName, mTvOpenName, mTvName, mTvAddress, mTvEndTime, mTvReceivedMode, mTvFightGroupPrice,
            mTvShop, mTvOpenNumber, mTvDiscountPrice;
    private TextView mTvReceivedName, mTvReceivedAddress;
    private String mAddress,mStoreId ;
    private int mPayWay = 1;   //0零钱（测试）  1 支付宝 2微信
    private List<ConsumerAddress.ConsumerData> consumerDataList;
    private GoodsInfoDetail.Convenient mConvenient;

    @Inject
    OpenFightGroupPresenter presenter;

    @Override
    protected int setView() {
        return R.layout.activity_open_fight_group;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        super.initView(savedInstanceState);
        DaggerHomeComponent.builder()
                .appComponent(App.getInstance().getAppComponent())
                .homeModule(new HomeModule(this))
                .build()
                .inject(this);
        setTbTitle("我要开团");
        setTbMenu(R.mipmap.icon_title_close);
        initView();
        initData();
    }

    private void initView() {
        RxUtils.bindEvents(getViewById(R.id.btn_cancel), this);  //取消
        RxUtils.bindEvents(getViewById(R.id.btn_confirm), this);  //确定
        RxUtils.bindEvents(getViewById(R.id.rl_address), this);  //收货地址
        RxUtils.bindEvents(getViewById(R.id.rl_receiving_name), this);  //默认地址
        mIvGood = getViewById(R.id.iv_good);
        mTvGoodName = getViewById(R.id.tv_good_name);   //名称
        mTvOpenName = getViewById(R.id.tv_open_name);  //开团人
        mTvName = getViewById(R.id.tv_name);
        mTvAddress = getViewById(R.id.tv_address);  //地址
        mTvEndTime = getViewById(R.id.tv_end_time); //结束时间
        mTvReceivedMode = getViewById(R.id.tv_received_mode);  //收货方式
        mTvFightGroupPrice = getViewById(R.id.tv_fight_group_price);  //开团价格
        mTvShop = getViewById(R.id.tv_shop);  //商品名称
        mTvOpenNumber = getViewById(R.id.tv_open_number);  //人数
        mTvDiscountPrice = getViewById(R.id.tv_discount_price);
        mTvReceivedName = getViewById(R.id.tv_received_name);
        mTvReceivedAddress = getViewById(R.id.tv_received_address);
        mRadioGroup = getViewById(R.id.radio_group);
        mRadioGroup.setOnCheckedChangeListener(this);


    }


    @Override
    protected void clickMenu() {
        super.clickMenu();
        finish();
    }

    @Override
    public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {

        switch (checkedId){
            case R.id.rb_alipay:   //支付宝
                mPayWay = 1;
                break;

            case R.id.rb_wechat:   //微信
                mPayWay = 2;
                break;
        }

    }
    @Override
    public void call(View v) {
        super.call(v);
        switch (v.getId()) {
            case R.id.btn_cancel:   //取消
                finish();
                break;
            case R.id.btn_confirm:  //确定
                if(mConvenient==null){
                    TipUtils.showToast(App.getInstance(),"加载中...",3);
                    return;
                }
                if(TextUtils.isEmpty(mTvAddress.getText().toString())){
                    TipUtils.showToast(App.getInstance(),"请选择收货地址！",3);
                    return;
                }
                if(TextUtils.isEmpty(mTvReceivedName.getText().toString())){
                    TipUtils.showToast(App.getInstance(),"请选择收货人地址！",3);
                    return;
                }
                presenter.openGroupPay(mPayWay,mGoodsId,mStoreId,mConvenient);
                break;
            case R.id.rl_address:  //收货地址
                Intent intent = new Intent(this, FightGroupAddressActivity.class);
                startActivityForResult(intent, RESULT_INTENT);
                break;
            case R.id.rl_receiving_name: //默认地址
                startActivity(new Intent(this, ReceivingAddressActivity.class));
                break;

        }
    }

    private void initData() {
        isEnable(false);
        mGoodsId = getIntent().getStringExtra("goods_id");
        mJson = getIntent().getStringExtra("json");
        try {
            String nickName = InfoProvider.getConsumerInfo(App.getInstance()).getNick_name();
            String mobile = InfoProvider.getUserInfo(App.getInstance()).getMobile();
            if (!TextUtils.isEmpty(mobile) && mobile.length() == 11) {
                mobile = mobile.substring(0, 3) + "****" + mobile.substring(7, mobile.length());
            }
            if(!TextUtils.isEmpty(nickName)&&!TextUtils.isEmpty(mobile)) {
                mTvOpenName.setText(nickName+"  "+mobile);
            }else if(TextUtils.isEmpty(nickName)&&!TextUtils.isEmpty(mobile)) {
                mTvOpenName.setText(mobile);
            }else if(!TextUtils.isEmpty(nickName)&&TextUtils.isEmpty(mobile)) {
                mTvOpenName.setText(nickName);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        receivePayResult();
        presenter.getGoodsInfoDetail(mGoodsId,"","goods.psGoodsDetailFind");
    }


    @Override
    protected void onResume() {
        super.onResume();
        consumerDataList = InfoProvider.getUserReceivingAddress(this);
        if (consumerDataList != null) {
            if (consumerDataList.size() > 0) {
                for (int i= 0;i<consumerDataList.size();i++){
                    if(TextUtils.equals(consumerDataList.get(i).getIs_major_addr(),"Y")){
                        mTvReceivedName.setText(consumerDataList.get(i).getConsignee() + "  " + consumerDataList.get(i).getMobile());
                        String area = AddressUtil.getSSQ(this,consumerDataList.get(i).getArea_id());
                        String address = consumerDataList.get(i).getAddress();
                        mTvReceivedAddress.setText(area + address);
                        mTvReceivedAddress.setVisibility(View.VISIBLE);
                    }
                }
            } else {
                mTvReceivedName.setText("");
                mTvReceivedName.setHint("请选择收货人地址");
                mTvReceivedAddress.setText("");
                mTvReceivedAddress.setVisibility(View.GONE);
            }
        }
    }

    @Override
    public void getGoodsInfoDetailSuccess(GoodsInfoDetail data) {
        if (data != null) {
            HashMap<String, String> docUrl = data.getDoc_url();
            mConvenient = data.getList().get(0);
            setGoodDetail(mConvenient, docUrl);
        }
    }

    @Override
    public void getGoodsInfoDetailFail(int code, String msg) {
        TipUtils.showToast(App.getInstance(),msg);
    }

    @Override
    public void payFail(int code, String msg) {
        TipUtils.showToast(App.getInstance(), getString(R.string.wallet_change_recharge_order_fail));
    }

    /**
     * 设置开团信息
     *
     * @param convenient
     * @param docUrl
     */
    private void setGoodDetail(GoodsInfoDetail.Convenient convenient, HashMap<String, String> docUrl) {
        mTvGoodName.setText(convenient.getTitle());
        mTvShop.setText(convenient.getTitle());
        mTvAddress.setText(convenient.getAddress());
        mTvEndTime.setText(convenient.getTs_date() + "小时");
        mTvOpenNumber.setText(convenient.getTs_min_num() + "人团");
        mTvFightGroupPrice.setText("¥" + convenient.getTs_price());
        mTvDiscountPrice.setText("¥" + convenient.getDiscount_price());
        String picInfo = convenient.getPic_info();
        if (!TextUtils.isEmpty(picInfo)) {
            try {
                JSONArray jsonArray = new JSONArray(picInfo);
                JSONObject jsonObject = jsonArray.getJSONObject(0);
                String img = jsonObject.getString("path_id");
                img = docUrl.get(img);
                GlideUtils.setRectImage(this,img, mIvGood);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    private void receivePayResult() {
        Disposable disposable = RxBus.get().toFlowable(PayResultBean.class).subscribe(new Consumer<PayResultBean>() {
            @Override
            public void accept(PayResultBean payResultBean) throws Exception {
                if (payResultBean != null) {
                    if (payResultBean.result == Constants.PAY_FIGHT_GROUP_SUCCESS) {
                        TipUtils.showToast(App.getInstance(), getString(R.string.wallet_change_recharge_success));
                        Intent intent = new Intent(OpenFightGroupActivity.this,FightGroupShareActivity.class);
                        intent.putExtra("type","open_fight");
                        intent.putExtra("json",mJson);
                        startActivity(intent);
                        finish();
                    } else if (payResultBean.result == Constants.PAY_RESULT_FAIL) {
                        TipUtils.showToast(App.getInstance(), getString(R.string.wallet_change_recharge_fail));
                    }
                }
            }
        });
        mCompositeDisposable.add(disposable);
    }
    //选择取货地址回调
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (data != null && RESULT_INTENT == requestCode) {
            mAddress = data.getStringExtra("address");
            mStoreId = data.getStringExtra("storeId");
            String storeName = data.getStringExtra("storeName");
            if (!TextUtils.isEmpty(mAddress)) {
                mTvAddress.setText(mAddress);
                mTvName.setVisibility(View.VISIBLE);
                mTvName.setText(storeName);
            }
        }
        super.onActivityResult(requestCode, resultCode, data);

    }

    @Override
    protected void onRefreshData() {

    }

    @Override
    public void showError(String msg) {

    }

}
